package com.leo.interceptor;

import com.leo.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @ClassName: HandlerInterceptor2
 * @Description: 测试拦截器2
 * 简单说明一下：本工程是采用xml方式注册的拦截器，因此可以直接依赖注入，
 * 如果是SpringBoot方式注册拦截器，不要使用new的方式创建拦截器对象，
 * 要把拦截器通过@Autowired注入进来，然后注册到Spring容器中，
 * 不然这个拦截器中通过依赖注入到的userInfoService永远是null
 * @Author: leo825
 * @Date: 2020-02-03 16:05
 * @Version: 1.0
 */
public class HandlerInterceptor2 extends HandlerInterceptorAdapter {

    @Autowired
    UserInfoService userInfoService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("HandlerInterceptor2 preHandle");
        HttpSession session = request.getSession();
        session.setAttribute("startTime",System.currentTimeMillis());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("HandlerInterceptor2 postHandle");
        //访问数据库
        List userInfoList = userInfoService.getUserInfoList();
        System.out.print("HandlerInterceptor2 信息: ");
        System.out.println(userInfoList);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("HandlerInterceptor2 afterCompletion");
        HttpSession session = request.getSession();
        long startTime = (long)session.getAttribute("startTime");
        System.out.println("HandlerInterceptor2 过滤的接口耗时：" + (System.currentTimeMillis() - startTime) + "ms");
    }
}
